<?php
namespace app\store\model;

use app\common\model\BaseModel;

class Poster extends BaseModel{
    protected $autoWriteTimestamp = true;

    //关联图片
    public function image(){
        return $this->hasOne(UploadFile::class,'file_id','imagesIds')
            ->bind(['domain','file_path']);
    }

    // 获取默认数据
    private function defaultData(){
        return [
            'imagesIds' => '',
            'width' => '400',
            'left' => '200',
            'top' => '600',
            'url' => '/share/index.html'
        ];
    }
    //获取设置信息
    public function detail($store_id){
        $r = self::where(['store_id'=>$store_id])
            ->with('image')
            ->findOrEmpty();
        if($r->isEmpty()){
            return $this->defaultData();
        }
        return $r;
    }

    //添加或更新设置
    public function setData($params){
        $store_id = getStoreId();
        if(is_array($params['imagesIds'])){
            $imagesIds = $params['imagesIds'][0];
        }else{
            $imagesIds = $params['imagesIds'];
        }
        $updateBool = false;
        $isEmpty = self::where(['store_id'=>$store_id])->findOrEmpty();
        if($isEmpty->isEmpty()){
            //添加
            $updateBool = $this->save([
                'store_id' => $store_id,
                'imagesIds' => $imagesIds,
                'width' => $params['width'],
                'left' => $params['left'],
                'top' => $params['top'],
                'url' => $params['url']
            ]);
        }else{
            $updateBool = self::where(['store_id'=>$store_id])
                ->save([
                    'imagesIds' => $imagesIds,
                    'width' => $params['width'],
                    'left' => $params['left'],
                    'top' => $params['top'],
                    'url' => $params['url']
                ]);
        }
        return $updateBool;
    }
}
